const router = require("koa-router")();
const Mock = require("mockjs");
const JWT=require('jsonwebtoken')
let { list } = Mock.mock({
  "list|50": [
    {
      img: "@image(100x100,@color)",
      title: "@ctitle(2)",
      city: "@city",
      id: "@id",
    }
  ]
});

let user=[{
  "username":"admin",
  "password":"admin",
  "row":"admin"
},{
  "username":"user",
  "password":"user",
  "row":"user"
}]



router.post('/sigin',(ctx)=>{
  let {username,password}=ctx.request.body
  let items=user.find((item)=>item.username==username)
  if (items) {
    ctx.body={
      code:400,
      msg:"账号已存在"
    }
  }else{
    user.push({...ctx.request.body,row:"admin"})

    ctx.body={
      code:200,
      msg:"注册成功"
    }
  }
})

router.post('/login',(ctx)=>{
  let {username,password}=ctx.request.body
  let items=user.find((item)=>item.username==username)
  if (items) {
    ctx.body={
      code:200,
      msg:"登录成功",
      row:items.row,
      token:JWT.sign(items.username,"dfghjkl")
    }
  }else{
    ctx.body={
      code:400,
      msg:"登录失败",
       
    }
  }
})






router.get("/list", (ctx, next) => {
  ctx.body = {
    code: 200,
    list,
  };
});

router.delete("/del", (ctx) => {
  let { id } = ctx.request.query;
  list = list.filter((item) => item.id !== id);
  ctx.body = {
    code: 200,
    msg: "删除成功",
  };
});

router.put("/add", (ctx) => {
  list.unshift({ ...ctx.request.body, id: Mock.mock("@id") });
  ctx.body = {
    code: 200,
    msg: "添加成功",
  };
});

router.put("/edit", (ctx) => {
  let { id } = ctx.request.body;
  let items = list.find((item) => item.id == id);
  if (items) {
    Object.assign(items, ctx.request.body);
    ctx.body = {
      code: 200,
      msg: "修改成功",
    };
  } else {
    ctx.body = {
      code: 400,
      msg: "修改失败",
    };
  }
});

router.get("/search", (ctx) => {
  let { value } = ctx.request.query;
  if (value !== "") {
    let items = list.filter(
      (item) =>
        item.title.includes(value) ||
        item.city.includes(value) ||
        item.id.includes(value)
    );
    ctx.body = {
      code: 200,
      items: items,
    };
  } else {
    ctx.body = {
      items: list,
    };
  }
});

module.exports = router;
